package com.JDBC;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * jdbc工具类
 *
 * @author jiangbang
 * @date 2016/10/20
 */
public class JDBCUtil {

    public static void main(String[] args) {
        JDBCUtil.getMysqlConn();
        System.out.println();
    }

    static Properties pros = null;  //可以帮助读取和处理资源文件中的信息
    static {  //加载JDBCTuil类的时候调用
        pros = new Properties();
        try {
            pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Connection getMysqlConn() {
        try {
            Class.forName(pros.getProperty("mysqlDriver"));
            return DriverManager.getConnection(pros.getProperty("mysqlURl"),pros.getProperty("mysqlUser"),pros.getProperty("mysqlPassword"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        //遵循 resultSet -->  statment -->connection这样的关闭顺序，一定要讲三个try分开写
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs) {
        //遵循 resultSet -->  statment -->connection这样的关闭顺序，一定要讲三个try分开写
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close( PreparedStatement ps) {
        try {
            if (ps != null) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
